package com.qingcheng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.qingcheng.pojo.goods.Goods;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.pojo.goods.Spu;
import com.qingcheng.service.goods.CategoryService;
import com.qingcheng.service.goods.SpuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.*;

@RestController
@RequestMapping("/item")
public class ItemController {
    @Reference
    private SpuService spuService; //将spu实现类注入


    @Autowired
    private TemplateEngine templateEngine;//将Spring集成的引擎注入


    @Value("${pagePath}")
    private String pagePath;

    @Reference
    private CategoryService categoryService;


    @GetMapping("/findGoodsById")
    public void findGoodById(String id){
        //根据id获取Goods对象
        Goods good = spuService.findGoodsById(id);
        //获取spu
        Spu spu = good.getSpu();

        //创建文件夹
        File dir=new File(pagePath);
        //判断文件夹是否存在，不存在就创建
        if(!dir.exists()){
            dir.mkdirs();
        }




        //获取sku集合
        List<Sku> skuList = good.getSkuList();

        Map urlMap=new HashMap();
        //为生成每个sku生成一个Url
        for (Sku sku : skuList) {
            if("1".equals(sku.getStatus())) {
                //获取每个sku拼接后的字符串，且顺序是按照先后顺序
                String speJson = JSON.toJSONString(JSON.parseObject(sku.getSpec()), SerializerFeature.MapSortField);
                //sku的id作为地址值，传入map集合
                urlMap.put(speJson, sku.getId() + ".html");
            }

        }



        for (Sku sku : skuList) {
            //创建Map集合，将数据封装进
            Map<String,Object> map=new HashMap<>();
            map.put("spu",spu);
            map.put("sku",sku);

            //将spu和sku的图片集合放入map中
            map.put("spuImages",spu.getImages().split(","));
            map.put("skuImages",sku.getImages().split(","));


            //将面包屑封装进map集合
            //获取所有Category集合
            List<String> categoryList=new ArrayList<String>();
            categoryList.add(categoryService.findById(spu.getCategory1Id()).getName());
            categoryList.add(categoryService.findById(spu.getCategory2Id()).getName());
            categoryList.add(categoryService.findById(spu.getCategory3Id()).getName());
            map.put("categoryNameList",categoryList);

            //添加商品参数和规格
            Map speItems=JSON.parseObject(sku.getSpec());  //将商品sku的规格封装进map集合
            Map paraItems=JSON.parseObject(spu.getParaItems()); //将商品spu的参数封装进map集合
            map.put("speItems",speItems);
            map.put("paraItems",paraItems);





//定义map集合  { "颜色":[{'option':'红色','check':true,url='红-32'},{'option':'黑色','check':false,'黑-32'}] ,"版本":[{'option':'64G','check':false,'红-64'},{'option':'32G','check':true,'红-32'} ]  }
            Map searchMap=new HashMap();
            //获取商品的规格，JSON转为Map集合  {"颜色":["粉色","黑色","蓝色"],"版本":["6GB+128GB","8GB+128GB"]}
            Map<String,Object> spuMap=JSON.parseObject(spu.getSpecItems());
            //遍历map集合
            Set<String> keySet = spuMap.keySet();
            for (String key : keySet) {  //{颜色、版本}
                List<Map> speList=new ArrayList<Map>();
                //获取键对应的值为List集合
                //遍历集合
                List<String> speValue=(List<String>) spuMap.get(key); //{"粉色","黑色","红色"}
                for (String value : speValue) {
                    //定义集合中的元素对象是map集合
                    Map<String,Object> speMap=new HashMap<String,Object>();
                    speMap.put("option",value); //{"颜色":"粉色","版本":"8G"}
                    if(speItems.get(key).equals(value)){  //判断此商品sku中的spe中key值对应的值是否是value
                        speMap.put("check",true);
                    }else {
                        speMap.put("check", false);
                    }
                    //获取此时Sku的Spe值
                    Map newMap=JSON.parseObject(sku.getSpec());
                    newMap.put(key,value);
                    String name = JSON.toJSONString(newMap, SerializerFeature.MapSortField);
                    speMap.put("url",urlMap.get(name));
                    speList.add(speMap);
                }
                //将集合封装进map集合
                searchMap.put(key,speList);
            }
            map.put("searchMap",searchMap);




            //创建上下文对象
            Context context=new Context();
            //数据模型，数据库查出响应对象，封装进map集合
            context.setVariables(map);
            //准备文件
            File file=new File(dir,sku.getId()+".html");
            try {
                //创建输出流对象
                PrintWriter printWriter= new PrintWriter(file,"UTF-8");
                //生成页面
                templateEngine.process("item",context,printWriter);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }
}
